package com.konsung.ksdc.manager.community;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.GroupNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.config.NetConfig;

import java.sql.SQLException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 联系人界面
 * Created by andy on 2017/4/24.
 */
public class ContactFragment extends Fragment {
    @Bind(R.id.lv_my_contact)
    ListView contactListView;
    @Bind(R.id.ll_new_contact)
    LinearLayout llNewContact;
    @Bind(R.id.ll_my_group)
    LinearLayout llMyGroup;

    private ContactListAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.fragment_my_contact, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initContactListView();
        initChatGroup();
        initNewContactBtnEvent();
        registerReceiver();
    }

    @Override
    public void onResume() {
        super.onResume();
        //初始化群组，如果没有群，不显示，有，显示
        initChatGroup();
        //添加或者删除好友实时显示数据
        initContactDatas();
    }

    /**
     * 初始化我的群聊数据
     */
    private void initChatGroup() {
        try {
            List<GroupNetBean> groups = DatabaseHelper.getHelper(getActivity()).getDao(GroupNetBean
                    .class).queryForEq("ownerId", NetConfig.currentUser.getUserId());
            if (groups != null) {
                if (groups.size() != 0) {
                    //显示群UI
                    llMyGroup.setVisibility(View.VISIBLE);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注册网络断开广播
     */
    private void registerReceiver() {
        IntentFilter intent = new IntentFilter();
        intent.addAction(BroadCastActions.ACTION_DELETE_CONTACT);
        intent.addAction(BroadCastActions.ACTION_RELOAD_CONTACTS);
        intent.addAction(BroadCastActions.ACTION_REQUEST_PASSED);
        getActivity().registerReceiver(receiver, intent);
    }

    /**
     * 广播接收者
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (BroadCastActions.ACTION_DELETE_CONTACT.equals(intent.getAction())) {
                initContactDatas();
            }
            if (BroadCastActions.ACTION_RELOAD_CONTACTS.equals(intent.getAction())) {
                initContactDatas();
            }
            if (BroadCastActions.ACTION_REQUEST_PASSED.equals(intent.getAction())) {
                initContactDatas();
            }
        }
    };

    /**
     * 初始化新的朋友按钮事件
     */
    private void initNewContactBtnEvent() {
        llNewContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ContactRequestActivity.class);
                startActivity(intent);
            }
        });
        llMyGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GroupListActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化联系人列表数据
     */
    private void initContactListView() {
        contactListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int
                    position, long l) {
                RegisterUserNetBean user = (RegisterUserNetBean) contactListView
                        .getItemAtPosition(position);

                if (Constants.TOPIC_KSBK.equals(user.getUserName())) {
                    Intent intent = new Intent(getActivity(), KonsungWikiActivity.class);
                    startActivity(intent);
                    return;
                }

                Intent intent = new Intent(getActivity(), ContactIndexActivity.class);

                Gson gson = new Gson();
                intent.putExtra("data", gson.toJson(user));
                startActivity(intent);
            }
        });

        initContactDatas();
    }

    /**
     * 初始化列表数据
     */
    private void initContactDatas() {
        // 初始化好友列表
        List<RegisterUserNetBean> contacts = findAllContacts();
        if (adapter == null) {
            adapter = new ContactListAdapter(contacts);
            contactListView.setAdapter(adapter);
        } else {
            adapter.setContacts(contacts);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 查询所有好友
     * @return 用户集合
     */
    private List<RegisterUserNetBean> findAllContacts() {
        RuntimeExceptionDao<RegisterUserNetBean, String> dao = DatabaseHelper
                .getHelper(getActivity())
                .getRuntimeExceptionDao(RegisterUserNetBean.class);
        return dao.queryForEq("ownerId", NetConfig.currentUser.getUserId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }
}
